<?php
namespace app\index\controller;

use think\Controller;
use think\Exception;
use think\Request;
use think\Session;
use think\View;

class Base extends Controller
{

    /**
     * 清除session
     */
    public function clear_session() {
        Session::clear();
        $this->redirect(url('member/index'));
    }

    /**
     * 清除session
     */
    public function clear_session2() {
        Session::clear();
    }

    /**
     * 微信关注引导页面
     */
    public function subscribe() {
        return view('public/subscribe');
    }

    /**
     * 发送短信验证码
     */
    public function send_code() {
        $mobile = input('param.mobile');
        $data = local_invoke_api('send_code', ['mobile' => $mobile, 'template_code' => 0]);
        return json($data);
    }

    /**
     * 根据经纬度获取地址信息
     * @return \think\response\Json
     */
    public function get_geocoder() {
        $location = input('param.lat') . ',' . input('param.lng');
        $data = \Map\Map::getGeocoder($location);
        return json($data);
    }

    /**
     * 检查是否登录
     */
    public function is_login() {
        if (!session('?member_id') || !session('?member_username')) {
            $this->error('未登录');
        } else {
            $this->success('已登录');
        }
    }

    /**
     * 图片上传
     */
    public function upload_image() {
        $data = \app\api\service\Upload::upload_image();
        return json($data);
    }

    /**
     * 获取统计数量
     * @return \think\response\Json
     */
    public function get_count_num() {
        $data = local_invoke_api('get_count_num', ['member_id' => session('?member_id') ? session('member_id') : 0]);
        return json($data);
    }

    /**
     * 获取七牛云token
     * @return \think\response\Json
     */
    public function get_qiniu_token() {
        $data = local_invoke_api('get_up_token');
        return json($data);
    }

    /**
     * 免责声明
     * @return \think\response\View
     */
    public function mianzeshenming() {
        return view('public/mianzeshenming');
    }

    /**
     * 活动条款
     * @return \think\response\View
     */
    public function activity_agreement() {
        return view('public/activity_agreement');
    }

    /**
     * 产品详情
     * @return \think\response\View
     */
    public function product_content() {
        $id = input('param.id', 0);
        if (!(int)$id) {
            $content = '参数错误！';
        } else {
            $content = model('product_details')->where('product_id', $id)->value('content');
        }

        $this->assign('content', $content);
        return view('public/product_content');
    }

    /**
     * 融云消息路由
     */
    public function receive_message() {
        $params = file_get_contents("php://input");
        $params = urldecode($params);
        $params = explode('&', $params);
        $data = [];
        file_put_contents(RUNTIME_PATH . 'rong_receive_message.txt', '');

        try {
            foreach ($params as $v) {
                $param = explode('=', $v);
                $val = $param[1];
                if ($param[0] == 'content') {
                    $val = json_decode($val, true);
                }
                $data[$param[0]] = $val;
                file_put_contents(RUNTIME_PATH . 'rong_receive_message.txt', $param[0] . '=' . $param[1] . " \n \n", FILE_APPEND);
            }


            // 组装融云消息记录数据
            $data = [
                'member_id' => $data['fromUserId'],
                'userId' => $data['fromUserId'],
                'targetId' => $data['toUserId'],
                'msg' => $data['content']['content'],
                'type' => $data['channelType'] == 'PERSON' ? 'friend' : 'group'
            ];
            model('rong_msg')->save($data);

            // 检查两个用户之间是否好友  首先获取缓存
            cache('friends_' .  $data['type'] . '_' . $data['userId'], null);
            if(!$friends = cache('friends_' .  $data['type'] . '_' . $data['userId'])) {
                // 如果没有缓存，先获取好友列表数据
                $friends = model('rong_member_friend')->where('user_id', $data['userId'])->where('type', $data['type'])->column('target_id');
                $friends = implode(',', $friends);
                cache('friends_' . $data['type'] . '_' . $data['userId'], $friends);
            }

            $friends = explode(',', $friends);

            if (!in_array($data['targetId'], $friends)) {
                // 如果两个人还不是好友，添加记录
                $friend_data = [
                    'user_id' => $data['userId'],
                    'target_id' => $data['targetId'],
                    'type' => $data['type'],
                    'group' => $data['type'] == 'kefu' ? 'kefu' : 'friend',
                    'update_time' => time(),
                ];
                model('rong_member_friend')->save($friend_data);
                // 更新缓存
                $friends = implode(',', $friends) . ',' . $data['targetId'];
                cache('friends_' .  $data['type'] . '_' . $data['userId'], $friends);
            } else {
                // 如果已经是好友，更新时间
                model('rong_member_friend')->save(['update_time' => time()], ['user_id' => $data['userId'], 'target_id' => $data['targetId'], 'type' => $data['type']]);
            }
        } catch (Exception $e) {
            file_put_contents(RUNTIME_PATH . 'rong_receive_message.txt', 'err====' . $e->getMessage() . " \n \n", FILE_APPEND);
        }


        return 200;
    }
}
